<template>
    <div class="sys-config-container flex flex-col">
        <a-card class="mb-2.5">
            <common-form
                :model="state.queryForm"
                name="menu-form"
                :btn-show="{
                    add:false
                }"
                @query="handleQuery"
                @reset="handleReset"
            >
                <a-form-item
                    label="配置名称"
                    name="name"
                    class="w-1/2.5"
                >
                    <a-input v-model:value="state.queryForm.name"/>
                </a-form-item>
                <a-form-item
                    label="配置编码"
                    name="code"
                    class="w-1/2.5"
                >
                    <a-input v-model:value="state.queryForm.code"/>
                </a-form-item>
                <a-form-item
                    label="分组编码"
                    name="groupCode"
                    class="w-1/3"
                >
                    <a-select v-model:value="state.queryForm.groupCode" placeholder="">
                        <a-select-option v-for="item in state.groupCodeOpts" :key="item" :value="item.value">
                            {{ item.label }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </common-form>
        </a-card>
        <a-card class="flex-1 card-table">
            <common-table 
                :columns="columns" 
                :cols-check-list="cloneDeep(columnsOrigin.filter(i=>i.key != 'operation'))"
                :data="state.tableData"
                :pagination="{
                        total: state.tableParams.total,
                        current: state.tableParams.page,
                        pageSize: state.tableParams.pageSize,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        pageSizeOptions:['2','5','10','20'],
                        showTotal:(total:number) => `总数: ${total}`
                }"
                :loading="state.loading"
                :show-table-opt="true"
                exportFileName="配置导出"
                @add="handleAdd"
                @change="changePagination"
                @print="handlePrint"
                @cols-checked="handleColsChecked"
            >
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'sysFlag'">
                        <a-tag color="green" v-if="record.sysFlag == 1">启用</a-tag>
                        <a-tag color="orange" v-else>禁用</a-tag>
                    </template>
                    <template v-if="column.dataIndex ==='history'">
                        <div style="cursor: pointer;">
                            <edit-record-history :row="record"/>
                        </div>
                    </template>
                    <template v-if="column.dataIndex === 'operation'">
                        <div class="w-full">
                            <a-button :icon="h(EditOutlined)" ghost type="primary" class="mr-1" @click="handleEdit(record)" >编辑</a-button>
                            <a-popconfirm
                                title="确定删除?"
                                @confirm="handleDelete(record)"
                            >
                                <a-button :icon="h(DeleteOutlined)" danger >删除</a-button>
                            </a-popconfirm>
                        </div>
                    </template>
                </template>
            </common-table>
        </a-card>
        <edit-config ref="editConfigRef" @handle-query="handleQuery"/>
    </div>
</template>

<script setup lang="ts" name="sysConfig">
import { reactive,h,ref,onMounted, computed } from 'vue'
import CommonForm from '@/components/common-form/index.vue'
import CommonTable from '@/components/common-table/index.vue'
import editRecordHistory from "@/components/self/edit-record-history.vue";
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import { apiSysConfigGroupListGet, apiSysConfigPagePost ,apiSysConfigDeletePost} from '@/api/sys/sysConfig';
import type { ResType } from '@/api/types';
import type { TableParamsResType } from '../onlineUser/type';
import type { ItemType } from './types';
import editConfig from './components/editConfig.vue';
import { showMsg } from '@/utils';
import printJs from 'print-js'
import { cloneDeep } from 'lodash';

defineOptions({
    name:"sysConfig"
})

const editConfigRef = ref<InstanceType<typeof editConfig>>()
const state = reactive({
    queryForm:{
        name:"",
        code:"",
        groupCode:""
    },
    tableData:[] as any[],
    tableParams: {
		page: 1,
		pageSize: 50,
		total: 0 as any,
	},
    loading:false,
    groupCodeOpts:[] as any[],
})

const columnsOrigin= reactive([
    {
        title: '序号',
        align: "center",
        dataIndex: 'index',
        key: 'index',
        width: 60,
        customRender: ({ index }:{index:number}) => {
            return `${ index + 1 }`;
        },
        fixed: 'left',
        isCheck:true,
        colSpan:1
    },
    {
        title: '配置名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 150,        
        isCheck:true
    },
    {
        title: '配置编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        width: 150,       
        isCheck:true
    },
    {
        title: '属性值',
        dataIndex: 'value',
        key: 'value',
        align: 'center',
        width: 150,       
        isCheck:true
    },
    {
        title: '内置参数',
        dataIndex: 'sysFlag',
        key: 'sysFlag',
        align: 'center',
        width: 150,       
        isCheck:true
    },
    {
        title: '分组编码',
        dataIndex: 'groupCode',
        key: 'groupCode',
        align: 'center',
        width: 150,       
        isCheck:true
    },
    {
        title: '排序',
        dataIndex: 'orderNo',
        key: 'orderNo',
        align: 'center',
        width: 150,
        sorter: (a: any, b: any) => a.orderNo - b.orderNo,       
        isCheck:true
    }, 
    {
        title: '修改记录',
        dataIndex: 'history',
        key: 'history',
        align: 'center',
        width: 150,       
        isCheck:true
    }, 
    {
        title: '操作',
        align: 'center',
        key:"operation",
        dataIndex: 'operation',
        width: 250,
        fixed: 'right',       
        isCheck:true
    }
])

// 初始化全部显示
const columns= ref(columnsOrigin.filter(i=>i.isCheck))

const handleColsChecked = (checkedKeys:string[])=>{
    // checkedKeys选中列表
    columnsOrigin.forEach(i=>{
        // 确保aTable组件的columns列一定有一列展示
        if(i.key != 'operation') 
            i.isCheck = checkedKeys.includes(i.key)
    })
    columns.value = columnsOrigin.filter(i=>i.isCheck)
}

const handleQuery = async ()=>{
    state.loading = true
    const params = Object.assign({},state.queryForm,state.tableParams)
    const res = await apiSysConfigPagePost(params) as ResType<TableParamsResType<ItemType>>
    state.tableData = res.data.result.items
    state.tableParams.total = res.data.result.total
    state.loading = false
}

const handleReset = ()=>{
    state.queryForm = {
        name:"",
        code:"",
        groupCode:""
    }
    handleQuery()
}

const handleEdit = (record:any)=>{
	editConfigRef.value?.handleOpen(record)
}

const handleAdd = ()=>{
	editConfigRef.value?.handleOpen({sysFlag: 2, orderNo: 100})
}

const handleDelete =async (record:any)=>{
	await apiSysConfigDeletePost({id:record.id})
    showMsg("删除成功",'success')
    handleQuery()
}
const changePagination = async(pagination:{current:number,pageSize:number})=>{
    state.tableParams.page = pagination.current
    state.tableParams.pageSize = pagination.pageSize
    await handleQuery()
}

// 获取分组列表
const getGroupList = async ()=>{
    const res = await apiSysConfigGroupListGet() as ResType<any[]>
    res.data.result.forEach((i:any)=>{
        state.groupCodeOpts.push({
            label:i,
            value:i
        })
    })
}

const handlePrint = ()=>{
    // 打印的列
    const columnsT = columns.value.filter(i=>i.key!='operation'&& i.key != 'history'&& i.key!='index').map(i=>{
        return {
            ...i,
            prop:i.key,
        }
    })
    let tableTh = ""
    let tableTrTd = ""
    let tableTd:any = {}

    // 自定义打印格式
    // 处理头部
    columnsT.forEach((i:any)=>{
        tableTh += `<th class="table-th">${i.title}</th>`;
    })
    state.tableData.forEach((val:any,key:number)=>{
    	if(!tableTd[key]) tableTd[key] = []
        // 处理每列
        columnsT.forEach((v:any)=>{
            if (v.prop === 'operation') {
				return;
			}
            if (v.type === 'text') {
				tableTd[key].push(`<td class="table-th table-center">${val[v.prop]}</td>`);
			} else if (v.type === 'image') {
				tableTd[key].push(`<td class="table-th table-center"><img src="${val[v.prop]}" style="width:${v.width}px;height:${v.height}px;"/></td>`);
			} else {
				tableTd[key].push(`<td class="table-th table-center">${val[v.prop]}</td>`);
			}
        })
        tableTrTd += `<tr>${tableTd[key].join('')}</tr>`; //将当前列组成一行
    })
    printJs({
		printable: `<div style=display:flex;flex-direction:column;text-align:center><h3>打印</h3></div><table border=1 cellspacing=0><tr>${tableTh}${tableTrTd}</table>`,
		type: 'raw-html',
		css: ['//at.alicdn.com/t/c/font_2298093_rnp72ifj3ba.css', '//unpkg.com/element-plus/dist/index.css'],
		style: `@media print{.mb15{margin-bottom:15px;}.el-button--small i.iconfont{font-size: 12px !important;margin-right: 5px;}}; .table-th{word-break: break-all;white-space: pre-wrap;}.table-center{text-align: center;}`,
	});
}

onMounted(async()=>{
    handleQuery()
    getGroupList()
})
</script>

<style lang="scss" scoped>
.sys-config-container{
    .card-table{
        :deep(.ant-card-body){
            height: 100%;
        }
    }
}
:deep(.ant-table-cell-fix-right){
    // right: 0 !important;
}
:deep(.ant-btn >span) {
    display:inline-flex!important;
}
</style>